<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体卡片区域 -->
    <el-card>
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" class="input-with-select" @clear="getUserList"
            clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="17">
          <!-- 添加用户button按键 -->
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 主体渲染表单部分 -->
      <el-table border stripe :data="userList">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username" width='100px'></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name" width='100px'></el-table-column>
        <el-table-column label="状态" prop="mg_state" width='100px'>
          <!-- 状态的作用域插槽 -->
          <template v-slot="scope">
            <!-- {{scope.row}} -->
            <!-- 绑定数据 -->
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)" inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <!-- 表单列表里操作部分 -->
        <el-table-column label="操作">

          <template v-slot="scope">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)" size='mini'></el-button>
            <!-- 删除 -->
            <el-button type=" danger" icon="el-icon-delete" @click="removeId(scope.row.id)" size='mini'></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" @click="setRole(scope.row)" size='mini'></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页列表 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3,4,5]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户区域 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="resetAddForm">
      <el-form ref="addFormRef" label-width="80px" :model="addForm" :rules="addFormRules">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机:" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户区域 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机:" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色管理区域 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" width="50%" @close="selectedRoleId=null">
      <!-- 渲染用户名和角色 -->
      <p>用户名:{{userInfo.username}}</p>
      <p>当前角色:{{userInfo.role_name}}</p>
      <p>
        <!-- 当前下拉列表 -->
        <el-select v-model="selectedRoleId" placeholder="请选择权限" style="text-align: center;">
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
          </el-select>
      </p>
      <template #footer>
        <el-button @click="roleDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="saveRole">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // @click="editDialogVisible=false"
  data () {
    // 修改验证规则
    const validateEmail = function (rule, value, callback) {
      const reg = /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (reg.test(value)) { callback() } else { callback(new Error('邮箱不符合格式')) }
    }
    const validateMobile = function (rule, value, callback) {
      const reg = /^1[3456789]\d{9}$/
      if (reg.test(value)) { callback() } else { callback(new Error('手机号不符合格式')) }
    }
    return {
      selectedRoleId: '',
      roleDialogVisible: false,
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {

      },
      addDialogVisible: false,
      editDialogVisible: false,
      userList: [],
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3-10之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在6-15之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }

        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }

        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }

        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }

        ]
      },
      userInfo: {},
      roleList: []
    }
  },
  methods: {
    async saveRole () {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      this.roleDialogVisible = false
      this.getUserList()
    },
    roleDialogClosed () {

    },
    // 点击弹出分配弹窗
    async setRole (row) {
      this.userInfo = row
      // console.log(this.userInfo)
      this.roleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      console.log(this.roleList)
    },
    // 根据当前id删除列表
    removeId (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.$message({ type: 'success', message: '删除成功!' })
          this.getUserList()
        })
        .catch(() => { this.$message({ type: 'info', message: '已取消删除' }) })
    },
    // 修改表单信息并验证
    editUserInfo () {
      // 先预验证，在发送ajax
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return console.log('获取布尔值失败')
        // console.log(valid)
        const { data: res } = await this.$http.put('users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('更新用户信息成功')
      })
    },
    // 重置修改弹框表单
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 查询获取当前点击修改用户信息
    async showEditDialog (id) {
      // console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败')
      }
      this.editForm = res.data

      this.editDialogVisible = true
    },
    saveAddForm () {
      this.$refs.addFormRef.validate(async bool => {
        if (!bool) return console.log('验证失败')
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加失败')

        this.addDialogVisible = false
        this.getUserList()
        this.$message.success('添加成功')
      })
    },
    resetAddForm () {
      this.$refs.addFormRef.resetFields()
      // this.$refs.editFormRef.resetFields()
    },
    async changeState (infoVal) {
      console.log(infoVal)
      const { data: res } = await this.$http.put(`users/${infoVal.id}/state/${infoVal.mg_state}`)

      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
    },
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res)

      this.total = res.data.total
      this.userList = res.data.users
      // console.log(this.total)
      // console.log(this.userList)
    },
    handleCurrentChange (current) {
      this.queryInfo.pagenum = current
      this.getUserList()
    },
    handleSizeChange (size) {
      this.queryInfo.pagesize = size
      this.getUserList()
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getUserList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
</style>
